package com.sinping.qh.api.auth;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.sinping.qh.api.exception.HandlerException;
import com.sinping.qh.api.support.*;
import com.sinping.qh.domain.auth.User;
import com.sinping.qh.domain.user.ContentInfo;
import com.sinping.qh.domain.user.UserInfo;
import com.sinping.qh.dto.admin.ApiUnitDto;
import com.sinping.qh.dto.admin.user.ApiUserDto;
import com.sinping.qh.dto.admin.lab.ApiUnitAndLabDto;
import com.sinping.qh.repository.mongo.user.ContentInfoRepository;
import com.sinping.qh.service.admin.IAddorEditUserService;
import com.sinping.qh.service.auth.*;
import com.sinping.qh.utils.mapper.JsonMapper;
import com.sinping.qh.utils.misc.IdGenerator;
import com.sinping.qh.utils.security.CryptoUtil;
import com.sinping.qh.utils.text.TextValidator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Date;
import java.util.Set;

/**
 * @author houjiawei
 * @copyright 2017 sinping.com 北京芯平科技股份有限公司. All rights reserved.
 * 本内容仅限于北京芯平科技股份有限公司内部传阅，禁止外泄以及用于其他的商业目的.
 * <p>
 * package com.sinping.woniu.api.auth;
 * /**
 * 前端控制器
 * @create 2017/12/18
 */
@Api(value = "admin用户管理", description = "用户管理API")
@RequestMapping(value = Const.ADMIN_URI, name = "用户管理")
@RestController
public class UserEndPoint {

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    @SuppressWarnings("SpringJavaAutowiringInspection")
    private ISessionService sessionService;
    @Autowired
    private IAddorEditUserService addorEditUserService;

    private final static Logger logger = LoggerFactory.getLogger(UserEndPoint.class);
    @Autowired
    private Validator globalValidator;

    @Autowired
    ContentInfoRepository contentInfoRepository;

    /**
     * 新增用户
     *
     * @param msg
     * @return ResDto
     */
    @ApiOperation(value = "新增用户", notes = "用户名 // 手机号<br>" +
            "密码 // 6-20位 字母、数字组成可加下划线 <br>" +
            "昵称 // 不做限制  ")
    @RequestMapping(value = "user/info", method = RequestMethod.POST, name = "新增用户")
    public ResDto insert(HttpServletRequest request, @ApiParam(name = "msg", value = "{\"user_name\":\"abcd\",\"full_name\":\"田田田\",\"telephone\":\"333\",\"email\":\"903@qq.com\",\"role_id\":\"03d8fef75368\"" +
            ",\"unit_id\":\"12345678\"}") @RequestParam(required = true) String msg) {
        ResDto resDto = new ResDto(ConstEum.SUCCESS);
        try {

            ApiUserDto apiUserDto = JsonMapper.defaultMapper().fromJson(msg, ApiUserDto.class);
            if (apiUserDto == null) {
                logger.error("参数为空或有不正确的数据格式");
                return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
            }
            Set<ConstraintViolation<ApiUserDto>> validate = globalValidator.validate(apiUserDto);
            if (!validate.isEmpty()) {
                for (ConstraintViolation<ApiUserDto> apiOrgSalesDTOConstraintViolation : validate) {
                    logger.info("必传参数 :{}", apiOrgSalesDTOConstraintViolation.getMessage());
                    return new ResDto(Const.PARAM_ERROR, apiOrgSalesDTOConstraintViolation.getMessage());
                }

            }

            try {
                return addorEditUserService.addUser(request, apiUserDto);
            } catch (Exception e) {
                logger.error("注册异常{}", e);
                resDto.setStatus(Const.SERVER_ERROR);
                resDto.setMsg("注册异常");
                return resDto;
            }


        } catch (DataIntegrityViolationException e) {
            logger.error(e.getMessage(), e);
            throw e;
        } catch (Exception e) {
            resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg(e.getMessage());
            logger.error(e.getMessage(), e);
            e.printStackTrace();
        }
        return resDto;
    }

    /**
     * 更新用户
     *
     * @param msg
     * @return ResDto
     */
    @ApiOperation(value = "更新用户", notes = "参数id必传")
    @RequestMapping(value = "user/info", method = RequestMethod.PUT, name = "更新用户")
    public ResDto updateById(HttpServletRequest request, @ApiParam(name = "msg", value = "{\"id\":\"xxxx\",\"user_name\":\"abcd\",\"full_name\":\"田田田\",\"telephone\":\"333\",\"email\":\"903@qq.com\",\"role_id\":\"03d8fef75368\"" +
            ",\"unit_id\":\"12345678\"}") @RequestParam(required = true) String msg) {

        ApiUserDto apiUserDto = JsonMapper.defaultMapper().fromJson(msg, ApiUserDto.class);
        if (apiUserDto == null) {
            logger.error("参数为空或有不正确的数据格式");
            return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
        }
        if (!StringUtils.isNotBlank(apiUserDto.getId())) {
            logger.info("必传参数 :{}", "id");
            return new ResDto(Const.PARAM_ERROR, "id");
        }
        Set<ConstraintViolation<ApiUserDto>> validate = globalValidator.validate(apiUserDto);
        if (!validate.isEmpty()) {
            StringBuffer buffer = new StringBuffer(64);
            for (ConstraintViolation<ApiUserDto> apiOrgSalesDTOConstraintViolation : validate) {
                buffer.append(apiOrgSalesDTOConstraintViolation.getMessage());
            }
            logger.info("必传参数 :{}", buffer.toString());
            return new ResDto(Const.PARAM_ERROR, buffer.toString());
        }
        return addorEditUserService.updateUser(request, apiUserDto);

    }

    /**
     * 删除用户
     *
     * @param id
     * @return ResDto
     */
    @ApiOperation(value = "删除用户", notes = "id参数必传")
    @RequestMapping(value = "/user/info/{id}", method = RequestMethod.DELETE, name = "删除用户")
    public ResDto deleteById(@ApiParam(name = "id", value = "245ad13d6ad4") @PathVariable(required = true) String id) {
        try {
            logger.info("入参 {}", id);
            if (!StringUtils.isNotBlank(id)) {
                logger.info("必传参数 :{}", "id");
                return new ResDto(Const.PARAM_ERROR, "必传参数 :id");
            }
            return addorEditUserService.deleteUser(id);
        } catch (Exception e) {
            logger.error("数据解析异常{}", e);
            ResDto resDto = new ResDto(Const.SERVER_ERROR, "数据解析异常");
            return resDto;
        }
    }

    /**
     * 获取单个用户
     *
     * @param id
     * @return ResDto
     */
    @ApiOperation(value = "获取单个用户", notes = "id参数必传")
    @RequestMapping(value = "/user/info/{id}", method = RequestMethod.GET, name = "获取单个用户")
    public ResDto selectById(@ApiParam(name = "id", value = "245ad13d6a0c5205d4") @PathVariable(required = true) String id) {
        try {
            logger.info("入参 {}", id);
            if (!StringUtils.isNotBlank(id)) {
                logger.info("必传参数 :{}", "id");
                return new ResDto(Const.PARAM_ERROR, "必传参数 :id");
            }
            return addorEditUserService.getUserDetail(id);
        } catch (Exception e) {
            logger.error("数据解析异常{}", e);
            ResDto resDto = new ResDto(Const.SERVER_ERROR, "数据解析异常");
            return resDto;
        }
    }


    /**
     * 用户列表,分页
     *
     * @param msg
     * @return ResDto
     */
    @ApiOperation(value = "用户列表,分页")
    @RequestMapping(value = "/user/info", method = RequestMethod.GET, name = "用户列表")
    public ResDto listPage(HttpServletRequest request,@ApiParam(name = "msg", value = "{\"page_size\":10, \"page_current\":1, \"order_column\":null, \"order_by\":null, \"condition\":{\"user_name\":\"zhangsan\",\"full_name\":\"张三\",\"manager_unit_name\":\"光电\",\"unit_id\":\"12324234\"}}") @RequestParam(required = true) String msg) {

        try {
            logger.info("入参 {}", msg);
            //1.String msg=> FrontPage page
            FrontPage page = JsonMapper.defaultMapper().fromJson(msg, FrontPage.class);
            if (page == null) {
                logger.error("参数为空或有不正确的数据格式");
                return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
            }
            ResDto resDto = addorEditUserService.getUserList(request,page);
            return resDto;
        } catch (Exception e) {
            logger.error("数据解析异常{}", e);
            ResDto resDto = new ResDto(Const.SERVER_ERROR, "数据解析异常");
            return resDto;
        }
    }

//    /**
//     * 获取院系、负责院系、实验室、负责实验室列表，不分页
//     */
//    @ApiOperation(value = "获取用户负责实验室/院系列表,不分页")
//    @RequestMapping(value = "/user/lab", method = RequestMethod.GET, name = "获取用户负责实验室/院系列表")
//    public ResDto getUnitList(HttpServletRequest request) {
//        try {
//
//            return addorEditUserService.getUserManagerUnitAndLabList(request);
//        } catch (Exception e) {
//            logger.error("数据解析异常{}", e);
//            ResDto resDto = new ResDto(Const.SERVER_ERROR, "数据解析异常");
//            return resDto;
//        }
//    }

////////////////////////////////////配置实验室 获取实验室列表拆分成四个接口，预备使用（先注释，勿删）//////////////////////////////////////////////////////

    @ApiOperation(value = "获取用户已负责院系列表,不分页",notes = "status:院系状态，  0：院系有效;获取用户负责的全部院系传空串")
    @RequestMapping(value = "/user/unit/user_manager", method = RequestMethod.GET, name = "获取用户已负责院系列表,不分页")
    public ResDto getUserManagerUnitList(HttpServletRequest request,@ApiParam(name = "msg", value = "{\"id\":\"用户id\",\"status\":\"0\"}") @RequestParam(required = true) String msg) {
        try {

            ApiUnitDto apiUnitDto = JsonMapper.defaultMapper().fromJson(msg, ApiUnitDto.class);
            if (apiUnitDto == null) {
                logger.error("参数为空或有不正确的数据格式");
                return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
            }


            if (StringUtils.isBlank(apiUnitDto.getId())){
                return new ResDto(Const.PARAM_ERROR,"用户id不为空");
            }
            return addorEditUserService.getUserManagerUnit(request,apiUnitDto.getId(), apiUnitDto.getStatus());
        } catch (Exception e) {
            logger.error("数据解析异常{}", e);
            ResDto resDto = new ResDto(Const.SERVER_ERROR,"数据解析异常");
            return resDto;
        }
    }
    @ApiOperation(value = "获取所有院系分组实验室列表,不分页")
    @RequestMapping(value = "/user/lab/all", method = RequestMethod.GET, name = "获取用户所有院系分组实验室列表,不分页")
    public ResDto getAllLabList() {
        try {

            return addorEditUserService.getAllLabList();
        } catch (Exception e) {
            logger.error("数据解析异常{}", e);
            ResDto resDto = new ResDto(Const.SERVER_ERROR,"数据解析异常");
            return resDto;
        }
    }

    @ApiOperation(value = "获取用户负责院系分组实验室列表,不分页")
    @RequestMapping(value = "/user/lab/user_manager/{id}", method = RequestMethod.GET, name = "获取用户负责院系分组实验室列表,不分页")
    public ResDto getUserManagerLabList(HttpServletRequest httpRequest, @ApiParam(name = "id", value = "245ad13d6a0c5205d4") @PathVariable(required = true) String id) {
        try {
            if (StringUtils.isBlank(id)){
                return new ResDto(Const.PARAM_ERROR,"用户id不为空");
            }

            return addorEditUserService.getUserManagerLabList(httpRequest,id);
        } catch (Exception e) {
            logger.error("数据解析异常{}", e);
            ResDto resDto = new ResDto(Const.SERVER_ERROR,"数据解析异常");
            return resDto;
        }
    }
//
//
//    /**
//     * 给用户配置实验室/院系
//     *
//     * @param request
//     * @param msg
//     * @return
//     */
//
//    @ApiOperation(value = "给用户配置实验室/院系", notes = "type:负责类型  0:院系  1:实验室")
//    @RequestMapping(value = "/user/lab", method = RequestMethod.POST, name = "给用户配置实验室/院系")
//    public ResDto AddUnitAndLabToUser(HttpServletRequest request, @ApiParam(name = "msg", value = "{\"user_id\":\"xxxx\",\"manager_unit_id\":\"xxxx\",\"manager_lab_id_list\":\"[xx,xx,xx]\",\"type\":\"1\"}") @RequestParam(required = true) String msg) {
//        ApiUnitAndLabDto apiUnitAndLabDto = JsonMapper.defaultMapper().fromJson(msg, ApiUnitAndLabDto.class);
//        if (apiUnitAndLabDto == null) {
//            logger.error("参数为空或有不正确的数据格式");
//            return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
//        }
//        Set<ConstraintViolation<ApiUnitAndLabDto>> validate = globalValidator.validate(apiUnitAndLabDto);
//        if (!validate.isEmpty()) {
//            for (ConstraintViolation<ApiUnitAndLabDto> apiOrgSalesDTOConstraintViolation : validate) {
//                logger.info("必传参数 :{}", apiOrgSalesDTOConstraintViolation.getMessage());
//                return new ResDto(Const.PARAM_ERROR, apiOrgSalesDTOConstraintViolation.getMessage());
//            }
//
//        }
//        if ("1".equals(apiUnitAndLabDto.getType())) {
//            if (apiUnitAndLabDto.getManagerLabIdList() == null) {
//                return new ResDto(Const.PARAM_ERROR, "实验室id不能为空");
//            }
//            if (apiUnitAndLabDto.getManagerLabIdList().isEmpty()) {
//                return new ResDto(Const.PARAM_ERROR, "实验室id不能为空");
//            }
//        }
//        try {
//            return addorEditUserService.addUnitAndLabToUser(apiUnitAndLabDto);
//        } catch (Exception e) {
//            logger.error("数据解析异常{}", e);
//            ResDto resDto = new ResDto(Const.SERVER_ERROR, "数据解析异常");
//            return resDto;
//        }
//    }


    /**
     * 给用户配置院系
     *
     * @param request
     * @param msg
     * @return
     */

    @ApiOperation(value = "给用户配置院系", notes = "type:负责类型  0:院系  1:实验室")
    @RequestMapping(value = "/user/unit_to_user", method = RequestMethod.POST, name = "给用户配置实验室")
    public ResDto AddUnitToUser(HttpServletRequest request, @ApiParam(name = "msg", value = "{\"user_id\":\"xxxx\",\"manager_unit_id_list\":[\"xx\",\"xx\"]}") @RequestParam(required = true) String msg) {
        ApiUnitAndLabDto apiUnitAndLabDto = JsonMapper.defaultMapper().fromJson(msg, ApiUnitAndLabDto.class);
        if (apiUnitAndLabDto == null) {
            logger.error("参数为空或有不正确的数据格式");
            return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
        }
        if (StringUtils.isBlank(apiUnitAndLabDto.getUser_id())) {
            return new ResDto(Const.PARAM_ERROR, "user_id不能为空");
        }
        if (apiUnitAndLabDto.getManagerUnitIdList() == null) {
            return new ResDto(Const.PARAM_ERROR, "院系id不能为空");
        }
        if (apiUnitAndLabDto.getManagerUnitIdList().isEmpty()) {
            return new ResDto(Const.PARAM_ERROR, "院系id不能为空");
        }

        try {
            return addorEditUserService.addUnitToUser(request, apiUnitAndLabDto);
        } catch (Exception e) {
            logger.error("数据解析异常{}", e);
            ResDto resDto = new ResDto(Const.SERVER_ERROR, "数据解析异常");
            return resDto;
        }
    }


    /**
     * 给用户配置实验室
     *
     * @param request
     * @param msg
     * @return
     */

    @ApiOperation(value = "给用户配置实验室", notes = "type:负责类型  0:院系  1:实验室")
    @RequestMapping(value = "/user/lab_to_user", method = RequestMethod.POST, name = "给用户配置实验室")
    public ResDto AddLabToUser(HttpServletRequest request, @ApiParam(name = "msg", value = "{\"user_id\":\"xxxx\",\"list\":[{\"manager_unit_id\":\"xxxx\",\"manager_lab_id_list\":[\"xx\",\"xx\"]},{\"manager_unit_id\":\"xxxx\",\"manager_lab_id_list\":[\"xx\",\"xx\"]}]}") @RequestParam(required = true) String msg) {
        ApiUnitAndLabDto apiUnitAndLabDto = JsonMapper.defaultMapper().fromJson(msg, ApiUnitAndLabDto.class);
        if (apiUnitAndLabDto == null) {
            logger.error("参数为空或有不正确的数据格式");
            return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
        }
        if (StringUtils.isBlank(apiUnitAndLabDto.getUser_id())) {
            return new ResDto(Const.PARAM_ERROR, "user_id不能为空");
        }
        if (apiUnitAndLabDto.getList() == null) {
            return new ResDto(Const.PARAM_ERROR, "实验室id不能为空");
        }
        if (apiUnitAndLabDto.getList().isEmpty()) {
            return new ResDto(Const.PARAM_ERROR, "实验室id不能为空");
        }
        if (StringUtils.isBlank(apiUnitAndLabDto.getList().get(0).getManagerUnitId())){
            return new ResDto(Const.PARAM_ERROR, "单位id不能为空");
        }
        if (apiUnitAndLabDto.getList().get(0).getManagerLabIdList()==null){
            return new ResDto(Const.PARAM_ERROR, "实验室id不能为空");
        }
        if (apiUnitAndLabDto.getList().get(0).getManagerLabIdList().isEmpty()){
            return new ResDto(Const.PARAM_ERROR, "实验室id不能为空");
        }

        try {
            return addorEditUserService.addLabToUser(request, apiUnitAndLabDto);
        } catch (Exception e) {
            logger.error("数据解析异常{}", e);
            ResDto resDto = new ResDto(Const.SERVER_ERROR, "数据解析异常");
            return resDto;
        }
    }

//
//    @ApiOperation(value = "删除用户配置实验室/院系", notes = "type:负责类型  0:院系  1:实验室")
//    @RequestMapping(value = "/user/lab", method = RequestMethod.DELETE, name = "删除用户配置实验室/院系")
//    public ResDto deleteUnitAndLabToUser(HttpServletRequest request, @ApiParam(name = "msg", value = "{\"user_id\":\"xxxx\",\"manager_unit_id\":\"xxxx\",\"manager_lab_id_list\":\"[xx,xx,xx]\",\"type\":\"1\"") @RequestParam(required = true) String msg) {
//        ApiUnitAndLabDto apiUnitAndLabDto = JsonMapper.defaultMapper().fromJson(msg, ApiUnitAndLabDto.class);
//        if (apiUnitAndLabDto == null) {
//            logger.error("参数为空或有不正确的数据格式");
//            return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
//
//        }
//        Set<ConstraintViolation<ApiUnitAndLabDto>> validate = globalValidator.validate(apiUnitAndLabDto);
//        if (!validate.isEmpty()) {
//            StringBuffer buffer = new StringBuffer(64);
//            for (ConstraintViolation<ApiUnitAndLabDto> apiOrgSalesDTOConstraintViolation : validate) {
//                buffer.append(apiOrgSalesDTOConstraintViolation.getMessage());
//            }
//            logger.info("必传参数 :{}", buffer.toString());
//            return new ResDto(Const.PARAM_ERROR, buffer.toString());
//        }
//        if ("1".equals(apiUnitAndLabDto.getType())) {
//            if (apiUnitAndLabDto.getManagerLabIdList() == null) {
//                return new ResDto(Const.PARAM_ERROR, "实验室id不能为空");
//            }
//            if (apiUnitAndLabDto.getManagerLabIdList().isEmpty()) {
//                return new ResDto(Const.PARAM_ERROR, "实验室id不能为空");
//            }
//        }
//
//        try {
//            return addorEditUserService.deleteUnitAndLabToUser(apiUnitAndLabDto);
//        } catch (Exception e) {
//            logger.error("数据解析异常{}", e);
//            ResDto resDto = new ResDto(Const.SERVER_ERROR, "数据解析异常");
//            return resDto;
//        }
//    }


    @ApiOperation(value = "删除用户配置实验室", notes = "type:负责类型  0:院系  1:实验室")
    @RequestMapping(value = "/user/lab_to_user", method = RequestMethod.DELETE, name = "删除用户配置实验室")
    public ResDto deleteLabToUser(HttpServletRequest request, @ApiParam(name = "msg", value = "{\"user_id\":\"xxxx\",\"list\":[{\"manager_unit_id\":\"xxxx\",\"manager_lab_id_list\":\"[xx,xx]\"},{\"manager_unit_id\":\"xxxx\",\"manager_lab_id_list\":\"[xx,xx]\"}]}") @RequestParam(required = true) String msg) {
        ApiUnitAndLabDto apiUnitAndLabDto = JsonMapper.defaultMapper().fromJson(msg, ApiUnitAndLabDto.class);
        if (apiUnitAndLabDto == null) {
            logger.error("参数为空或有不正确的数据格式");
            return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");

        }
        if (StringUtils.isBlank(apiUnitAndLabDto.getUser_id())) {
            return new ResDto(Const.PARAM_ERROR, "user_id不能为空");
        }
        if (apiUnitAndLabDto.getList() == null) {
            return new ResDto(Const.PARAM_ERROR, "实验室id不能为空");
        }
        if (apiUnitAndLabDto.getList().isEmpty()) {
            return new ResDto(Const.PARAM_ERROR, "实验室id不能为空");
        }
        if (StringUtils.isBlank(apiUnitAndLabDto.getList().get(0).getManagerUnitId())){
            return new ResDto(Const.PARAM_ERROR, "单位id不能为空");
        }
        if (apiUnitAndLabDto.getList().get(0).getManagerLabIdList()==null){
            return new ResDto(Const.PARAM_ERROR, "实验室id不能为空");
        }
        if (apiUnitAndLabDto.getList().get(0).getManagerLabIdList().isEmpty()){
            return new ResDto(Const.PARAM_ERROR, "实验室id不能为空");
        }



        try {
            return addorEditUserService.deleteLabToUser(request,apiUnitAndLabDto);
        } catch (Exception e) {
            logger.error("数据解析异常{}", e);
            ResDto resDto = new ResDto(Const.SERVER_ERROR, "数据解析异常");
            return resDto;
        }
    }

    @ApiOperation(value = "删除用户配置院系", notes = "type:负责类型  0:院系  1:实验室")
    @RequestMapping(value = "/user/unit_to_user", method = RequestMethod.DELETE, name = "删除用户配置院系")
    public ResDto deleteUnitToUser(HttpServletRequest request, @ApiParam(name = "msg", value = "{\"user_id\":\"xxxx\",\"manager_unit_id_list\":[\"xx\",\"xx\"]}") @RequestParam(required = true) String msg) {
        ApiUnitAndLabDto apiUnitAndLabDto = JsonMapper.defaultMapper().fromJson(msg, ApiUnitAndLabDto.class);
        if (apiUnitAndLabDto == null) {
            logger.error("参数为空或有不正确的数据格式");
            return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");

        }
            if (StringUtils.isEmpty(apiUnitAndLabDto.getUser_id())){
                return new ResDto(Const.PARAM_ERROR, "用户id不能为空");
            }

            if (apiUnitAndLabDto.getManagerUnitIdList() == null) {
                return new ResDto(Const.PARAM_ERROR, "院系id不能为空");
            }
            if (apiUnitAndLabDto.getManagerUnitIdList().isEmpty()) {
                return new ResDto(Const.PARAM_ERROR, "院系id不能为空");
            }

        try {
            return addorEditUserService.deleteUnitToUser(request,apiUnitAndLabDto);
        } catch (Exception e) {
            logger.error("数据解析异常{}", e);
            ResDto resDto = new ResDto(Const.SERVER_ERROR, "数据解析异常");
            return resDto;
        }
    }

    /**
     * 用户重置密码
     *
     * @param msg
     * @return ResDto
     */
    @ApiOperation(value = "重置密码", notes = "id，new_password参数不可为空，且位数与格式正确", consumes = MediaTypes.TEXT_HTML_UTF_8)
    @RequestMapping(value = "/user/password", method = RequestMethod.PUT, name = "重置密码")
    public ResDto reset(@ApiParam(name = "msg", value = "{\"id\":\"1233\",\"new_password\":\"abc\"}") @RequestParam String msg) {

        ResDto resDto = new ResDto(ConstEum.SUCCESS);
        try {
            User user = JsonMapper.defaultMapper().fromJson(msg, User.class);
            if (user == null) {
                resDto = new ResDto(ConstEum.PARAM_ERROR);
                resDto.setMsg("参数为空或有不正确的数据格式");
                return resDto;
            }
            if (StringUtils.isEmpty(user.getId())) {
                resDto = new ResDto(ConstEum.PARAM_ERROR);
                resDto.setMsg("用户id不能为空");
                return resDto;
            }

            if (StringUtils.isEmpty(user.getNewContent())) {
                resDto = new ResDto(ConstEum.PARAM_ERROR);
                resDto.setMsg("密码不能为空");
                return resDto;
            }
            User oldUser = userService.selectById(user.getId());
            if (null == oldUser) {
                resDto = new ResDto(ConstEum.PARAM_ERROR);
                resDto.setMsg("用户不存在");
            }
            UserInfo one = userService.findMongoUserExist(user);
            if (one == null) {
                return new ResDto(Const.SERVER_ERROR, "用户不存在");
            }
            /***验证密码规则*/
            if (!TextValidator.validateContentSimple(user.getNewContent())) {
                resDto = new ResDto(ConstEum.PARAM_ERROR);
                resDto.setMsg("密码格式错误");
                return resDto;
            }
            ContentInfo contentInfo=contentInfoRepository.findContentInfoByUserId(oldUser.getId());
            byte[] salt=null;
            if(contentInfo!=null){
                //如果有盐值重新生成盐值
                salt= CryptoUtil.createSalt();
                contentInfo.setSalt(Base64Utils.encodeToString(salt));
                contentInfo.setGmtModified(new Date());
                contentInfoRepository.save(contentInfo);
            }
            else{
                contentInfo=new ContentInfo();
                contentInfo.setId(IdGenerator.uuid2().toString());
                contentInfo.setUserId(oldUser.getId());
                salt= CryptoUtil.createSalt();
                contentInfo.setSalt(Base64Utils.encodeToString(salt));
                contentInfo.setGmtCreated(new Date());
                contentInfo.setGmtModified(new Date());
                contentInfoRepository.save(contentInfo);
            }

                user.setContent(CryptoUtil.sha256(salt, user.getNewContent()));
                boolean update = userService.updateById(user);
                if (!update) {
                    return new ResDto(Const.SERVER_ERROR, "修改失败");
                }
                //更新mongoDB用户信息
                if (update) {
                    one.setContent(user.getContent());
                    try {
                        userService.updateMongoUserInfo(one);
                    } catch (Exception e) {
                        e.printStackTrace();
                        userService.updateById(oldUser);
                        return new ResDto(Const.SERVER_ERROR, "修改失败");
                    }
                }


        } catch (DataIntegrityViolationException e) {
            logger.error(e.getMessage(), e);
            throw e;
        } catch (Exception e) {
            resDto = new ResDto(ConstEum.SERVER_ERROR);
            resDto.setMsg(e.getMessage());
            logger.error(e.getMessage(), e);
            e.printStackTrace();
        }
        return resDto;
    }
    @ApiOperation(value = "获取所有角色,不分页")
    @RequestMapping(value = "/user/role", method = RequestMethod.GET, name = "获取角色列表,不分页")
    public ResDto getAllRoleList() {
        try {

            return addorEditUserService.getRoleList();
        } catch (Exception e) {
            logger.error("数据解析异常{}", e);
            ResDto resDto = new ResDto(Const.SERVER_ERROR,"数据解析异常");
            return resDto;
        }
    }


    /***
     * 根据用户名判断是否存在用户
     * @param username
     * @return boolean
     */
    private boolean getExistUserByUserName(String username) {
        User existUserName = new User();
        existUserName.setUsername(username);
        existUserName.setDeleted(0);
        EntityWrapper paramEntity = new EntityWrapper();
        paramEntity.setEntity(existUserName);
        User existUser = userService.selectOne(paramEntity);
        if (null != existUser) {
            return true;
        }
        return false;
    }

}
